package utils

import (
	"io/ioutil"
	"gopkg.in/yaml.v2"
	"time"
	"os"
	"log"
)

type Config struct {
	Server      Server
	Database    Database
	YouZan      YouZan
	GlobalToken string
}
type Server struct {
	Mode        string
	NetTypes    string
	Address     string
	Port        int
	TlsCertFile string
	TlsKeyFile  string
	SysLogFmt   string
	WebLogFmt   string
}

type YouZan struct {
	ClientId     string
	ClientSecret string
	KdtId        int
	TimeWait     time.Duration
}

type Database struct {
	Prefix       string
	Address      string
	Name         string
	User         string
	Pass         string
	Port         int
	MaxOpenConns int
	MaxIdleConns int
}

const (
	CONFIGFILE = "config.yaml"
)

var (
	config *Config
	status bool
)

func init() {
	log.Println("[SYS]", time.Now().Local().Format("01-02 15:04:05"), "▶ System [Config loaded]")
	config = new(Config)
	if _, err := os.Stat(CONFIGFILE); err == nil {
		status = loadFromFile()
	}
	if !status {
		loadFromDefault()
	}
}

func loadFromFile() bool {
	fileBytes, err := ioutil.ReadFile(CONFIGFILE)
	if err != nil {
		return false
	}
	if err = yaml.Unmarshal(fileBytes, config); err != nil {
		return false
	}
	return true
}

func loadFromDefault() {
	db := Database{
		Prefix:       "",
		Address:      "localhost",
		Name:         "housirvip",
		Port:         5432,
		User:         "housirvip",
		Pass:         "",
		MaxIdleConns: 5,
		MaxOpenConns: 10,
	}
	youzan := YouZan{
		ClientId:     "xxxx",
		ClientSecret: "xxxx",
		KdtId:        666,
		TimeWait:     5 * time.Minute,
	}
	server := Server{
		Mode:        "release",
		NetTypes:    "http",
		Address:     "",
		Port:        8100,
		TlsCertFile: "",
		TlsKeyFile:  "",
		SysLogFmt:   `%{time:01-02 15:04:05} ▶ %{color}System %{message}%{color:reset}`,
		WebLogFmt:   `%{time:01-02 15:04:05} ▶ %{color}%{message}%{color:reset}`,
	}
	config = &Config{
		Server:      server,
		Database:    db,
		YouZan:      youzan,
		GlobalToken: "BeSureToChange",
	}
	data, err := yaml.Marshal(config)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	err = ioutil.WriteFile(CONFIGFILE, data, os.ModePerm)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
}

func GetConfig() Config {
	return *config
}
